package com.captjack.netty.httpserver.server;

import com.captjack.netty.httpserver.config.NettyHttpServerConfig;
import com.captjack.netty.httpserver.handler.NettyHttpServerHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpServerCodec;

/**
 * @author admin
 */
public final class NettyHttpServer {

    /**
     *
     */
    private final NettyHttpServerConfig nettyHttpServerConfig;

    /**
     *
     */
    private final NettyHttpServerHandler nettyHttpServerHandler;

    /**
     * 开始监听
     *
     * @throws Exception 异常
     */
    public void startListen() throws Exception {
        // boss
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        // worker
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        // serverBootstrap
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        try {
            // 启动
            serverBootstrap.channel(NioServerSocketChannel.class)
                    //
                    .group(bossGroup, workerGroup)
                    //
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    //
                    .option(ChannelOption.SO_BACKLOG, 1024)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            //
                            ch.pipeline().addLast("http-decoder", new HttpServerCodec());
                            //
                            ch.pipeline().addLast(nettyHttpServerHandler);
                        }
                    });
            // 绑定端口开始监听
            ChannelFuture future = serverBootstrap.bind(nettyHttpServerConfig.getListenPort()).sync();
            //
            future.channel().closeFuture().sync();
        } finally {
            // close
            bossGroup.shutdownGracefully();
            // close
            workerGroup.shutdownGracefully();
        }
    }

    public NettyHttpServer(NettyHttpServerConfig nettyHttpServerConfig, NettyHttpServerHandler nettyHttpServerHandler) {
        this.nettyHttpServerConfig = nettyHttpServerConfig;
        this.nettyHttpServerHandler = nettyHttpServerHandler;
    }

}
